package com.project.server.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.server.common.api.Result;
import com.project.server.dto.*;
import com.project.server.entity.SysUser;
import com.project.server.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @GetMapping("/info")
    public Result<SysUser> getUserInfo(HttpServletRequest request) {
        return Result.success(sysUserService.getById(getCurrentUserId(request)));
    }

    @GetMapping("/list")
    public Result<Page<SysUser>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) Integer roleId) {

        UserQueryDTO query = new UserQueryDTO();
        query.setUsername(username);
        query.setRealName(realName);
        query.setRoleId(roleId);

        return Result.success(sysUserService.getUserPage(current, size, query));
    }

    @PostMapping
    public Result<Void> add(@RequestBody UserDTO userDTO) {
        sysUserService.saveUser(userDTO);
        return Result.success();
    }

    @PutMapping
    public Result<Void> update(@RequestBody UserDTO userDTO) {
        sysUserService.updateUser(userDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        sysUserService.removeById(id);
        return Result.success();
    }

    @PutMapping("/status")
    public Result<Void> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        sysUserService.updateStatus(id, status);
        return Result.success();
    }

    @PostMapping("/password")
    public Result<Void> resetPassword(@RequestBody PasswordUpdateDTO passwordUpdateDTO,HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        SysUser user = new SysUser();
        user.setId(userId);
        user.setPassword(passwordEncoder.encode(passwordUpdateDTO.getNewPassword()));
        sysUserService.updateById(user);
        return Result.success();
    }
}
